#!/bin/bash

TAR_URL="https://mirrors.tuna.tsinghua.edu.cn/mysql/downloads/MySQL-8.0/mysql-8.0.26-linux-glibc2.17-x86_64-minimal-rebuild.tar.xz"
TAR_NAME="mysql-8.0.26.tar.xz"

INSTALL_DIR="/opt/mysql"
DATA_DIR="/opt/data"

MYSQL_GROUP="mysql"
MYSQL_USER="mysql"

function log() {
  echo --$(date "+%Y-%m-%d %H:%M:%S")-- $1
}

function checkTarFile() {
  if [ ! -f $TAR_NAME ]; then
    wget -c $TAR_URL -O $TAR_NAME
    log "download $TAR_NAME ...... OK"
  else
    log "check $TAR_NAME ...... OK"
  fi
}

function checkInstallDir() {
  if [ -d "/usr/local/mysql" ]; then
    log "It seems there is /usr/local/mysql already, please delete it first!"
    exit 1
  fi

  if [ ! -d "${INSTALL_DIR}" ]; then
    mkdir -p ${INSTALL_DIR}
  else
    log "It seems there is ${INSTALL_DIR} already, please delete it first!"
    exit 1
  fi

  if [ ! -d "${DATA_DIR}" ]; then
    mkdir -p ${DATA_DIR}
  else
    log "It seems there is ${DATA_DIR} already, please delete it first!"
    exit 1
  fi

  log "check install dir ...... OK"

  tar -xf ${TAR_NAME} -C ${INSTALL_DIR} --strip-components 1
  ln -s ${INSTALL_DIR} /usr/local/mysql

  log "untar file ...... OK"
}

function checkUserGroup() {
  id -u ${MYSQL_USER} &>/dev/null
  if [ $? -ne 0 ]; then
    groupadd ${MYSQL_GROUP}
    useradd -r -g ${MYSQL_GROUP} -s /bin/false ${MYSQL_USER}
    chown -R mysql:mysql ${DATA_DIR}
    chmod 750 ${DATA_DIR}
    log "check user and user_group ...... OK"
  else
    log "It seems there is user:$MYSQL_USER already"
  fi
}

function initMyCnf() {
  if [ -f /etc/my.cnf ]; then
    mv /etc/my.cnf /etc/my.cnf.$(date "+%Y%m%d%H%M%S")
    log "It seems there is '/etc/my.cnf' already,backup '/etc/my.cnf' ...... OK"
  fi

  cat >>/etc/my.cnf <<EOF
[client]
port= 3306
socket= /tmp/mysql.sock
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
user=mysql
port= 3306
socket= /tmp/mysql.sock
server-id = 1
basedir= /usr/local/mysql
datadir= ${DATA_DIR}
EOF

  log "init /etc/my.cnf ...... OK"
}

function initDatabase() {
  ${INSTALL_DIR}/bin/mysqld --initialize-insecure --user=${MYSQL_USER} --basedir=${INSTALL_DIR} --datadir=${DATA_DIR}
  [ $? -ne 0 ] && exit 1
  log "init database ...... OK"

  cp ${INSTALL_DIR}/support-files/mysql.server /etc/init.d/mysql.server
  chmod +x /etc/init.d/mysql.server

  log "/etc/init.d/mysql.server ...... OK"
}

checkTarFile
checkInstallDir
checkUserGroup
initMyCnf
initDatabase

log "mysql installed successfully!"
echo ""
log "useful tip:"
log "/etc/init.d/mysql.server start"
echo ""
log "/usr/local/mysql/bin/mysqladmin -u root password $mysqlrootpwd"
log "/usr/local/mysql/bin/mysql -u root -p$mysqlrootpwd"
echo ""
log "CREATE USER 'username'@'%' IDENTIFIED BY 'password';"
log "SET PASSWORD FOR 'username'@'%' = PASSWORD('newpassword');"
log "GRANT ALL ON *.* TO 'username'@'%';"
